package cn.lblbc.stopwatch
/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》http://lblbc.cn/blog
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：蓝不蓝编程
 */
object TimeUtil {
    fun formatTime(time: Long): String {
        val timeStr: String
        val hour: Long
        var minute: Long
        var second: Long
        val millisecond: Long
        if (time <= 0) return "00:00:00.000" else {
            second = time / 1000
            minute = second / 60
            millisecond = time % 1000
            if (second < 60) {
                timeStr = "00:00:" + fillZeros(second) + "." + fillZerosForMilliSeconds(millisecond)
            } else if (minute < 60) {
                second %= 60
                timeStr =
                    "00:" + fillZeros(minute) + ":" + fillZeros(second) + "." + fillZerosForMilliSeconds(
                        millisecond
                    )
            } else { //数字>=3600 000的时候
                hour = minute / 60
                minute %= 60
                second = second - hour * 3600 - minute * 60
                timeStr =
                    fillZeros(hour) + ":" + fillZeros(minute) + ":" + fillZeros(second) + "." + fillZerosForMilliSeconds(
                        millisecond
                    )
            }
        }
        return timeStr
    }

    private fun fillZeros(time: Long): String { //时分秒的格式转换
        return if (time in 0..9) "0$time" else "" + time
    }

    private fun fillZerosForMilliSeconds(time: Long): String { //毫秒的格式转换
        val retStr: String = when (time) {
            in 0..9 -> "00$time"
            in 10..99 -> "0$time"
            else -> "" + time
        }
        return retStr
    }
}